package org.jeecg.modules.assets.service.impl;

import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.assets.dto.*;
import org.jeecg.modules.assets.entity.*;
import org.jeecg.modules.assets.mapper.*;
import org.jeecg.modules.assets.service.IAssetsItemService;
import org.jeecg.modules.assets.service.IAssetsRandomStockItemService;
import org.jeecg.modules.assets.service.IAssetsRandomStockService;
import org.jeecg.modules.assets.service.IAssetsStartService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 抽盘管理
 * @Author: jeecg-boot
 * @Date: 2023-12-13
 * @Version: V1.0
 */
@Service
public class AssetsRandomStockServiceImpl extends ServiceImpl<AssetsRandomStockMapper, AssetsRandomStock> implements IAssetsRandomStockService {

    @Autowired
    private IAssetsStartService assetsStartService;

    @Autowired
    private IAssetsItemService assetsItemService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IAssetsRandomStockItemService assetsRandomStockItemService;

    @Autowired
    private AssetsRandomStockItemMapper storageRandomStockItemMapper;

    @Autowired
    private WechatUtils wechatUtils;

    @Autowired
    private AssetsItemMapper assetsItemMapper;

    @Autowired
    private DeptExtMapper deptextMapper;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    @Autowired
    private ISysBaseAPI isysBaseAPI;

    @Override
    public Result startAssets(StartAssetsDTO startAssets) {
        //资产管理系统优化
        //获取当前用户
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        AssetsStart assetsStart = new AssetsStart();
        assetsStart.setStatus("1");
        //抽盘
        assetsStart.setStartType("2");
        assetsStartService.save(assetsStart);
        AssetsRandomStock assetsRandomStock = new AssetsRandomStock();
        assetsRandomStock.setStatus("1");
        //判断部门是否有值
        if(startAssets.getDeptId()!=null){
            assetsRandomStock.setDeptId(startAssets.getDeptId());
            QueryWrapper qw = new QueryWrapper();
            qw.eq("dept_id", startAssets.getDeptId());
            DeptExt deptExt = deptextMapper.selectOne(qw);
            assetsRandomStock.setDeptName(deptExt.getDeptName());
        }
        assetsRandomStock.setInventoryUser(user.getRealname());
        assetsRandomStock.setCreateTime(new Date());
        assetsRandomStock.setUpdateTime(new Date());
        assetsRandomStock.setDeptId(startAssets.getDeptId());
        assetsRandomStock.setCompany(startAssets.getCompany());
        assetsRandomStock.setCompanyName(startAssets.getCompanyName());
        String baseBillNo = "GZCP-" + sdf.format(new Date());
        Object o = redisUtil.get(baseBillNo);
        String formattedNumber;
        if (o == null) {
            redisUtil.set(baseBillNo, 1);
            redisUtil.expire(baseBillNo, 60 * 60 * 24);
            formattedNumber = String.format("%03d", 1);
        } else {
            int i = Integer.parseInt(o.toString()) + 1;
            redisUtil.set(baseBillNo, i);
            redisUtil.expire(baseBillNo, 60 * 60 * 24);
            formattedNumber = String.format("%03d", i);
        }
        assetsRandomStock.setBillNo(baseBillNo + "-" + formattedNumber);

        this.save(assetsRandomStock);

        return Result.OK("添加成功", assetsRandomStock.getBillNo());
    }

    /**
     * 获取抽盘当前信息
     *
     * @param assetsRandomStock
     * @param page
     * @return
     */
    @Override
    public AssetsListRandomDTO getUsetAssetsInfo(AssetsRandomStock assetsRandomStock, Page page, Integer queryType) {
        AssetsListRandomDTO assetsListDTO = new AssetsListRandomDTO();
        assetsListDTO.setRandomName(assetsRandomStock.getInventoryUser());
        assetsListDTO.setDeptName(assetsRandomStock.getDeptName());
        assetsListDTO.setUserName(assetsListDTO.getUserName());
        assetsListDTO.setStatus(assetsRandomStock.getStatus());
        assetsListDTO.setBadNum(assetsRandomStock.getBadNum());
        assetsListDTO.setCompany(assetsRandomStock.getCompany());
        assetsListDTO.setCompanyName(assetsRandomStock.getCompanyName());
        assetsListDTO.setAssetsNum(TypeUtils.castToLong(assetsRandomStock.getWithdrawalNum()));
        if (Objects.equals(1, queryType)) {
            //获取当前登录人
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            Page<AssetsRandomStockItem> assetsItem = storageRandomStockItemMapper.getAssetsItem(page, assetsRandomStock.getId(), user.getRealname());
            assetsListDTO.setItemPages(assetsItem);
            return assetsListDTO;
        } else {
            Page<AssetsRandomStockItem> assetsItem = storageRandomStockItemMapper.getAssetsItem(page, assetsRandomStock.getId(), null);
            assetsListDTO.setItemPages(assetsItem);
            return assetsListDTO;
        }


    }

    @Override
    public void optionAssetsItem(OptionAssetsItemDTO optionAssetsItemDTO) {
        //根据抽盘单号获取抽盘信息
        QueryWrapper qw = new QueryWrapper();
        qw.eq("bill_no", optionAssetsItemDTO.getBillNo());
        AssetsRandomStock assetsRandomStock = this.getOne(qw);
        saveStockItem(optionAssetsItemDTO, assetsRandomStock);
    }

    @Override
    public void endAssets(EndAssetsDTO endAssetsDTO) {
        QueryWrapper qwRandom = new QueryWrapper();
        qwRandom.eq("bill_no", endAssetsDTO.getBillNo());
        AssetsRandomStock assetsRandomStock = this.getOne(qwRandom);
        //查询明细数量
        QueryWrapper<AssetsRandomStockItem> qw = new <AssetsRandomStockItem>QueryWrapper();
        qw.eq("apply_id", assetsRandomStock.getId());
        List<AssetsRandomStockItem> assetsRandomStockItems = storageRandomStockItemMapper.selectList(qw);
        assetsRandomStock.setWithdrawalNum(assetsRandomStockItems.size());
        long count = assetsRandomStockItems.stream().filter(item -> Objects.equals("2", item.getRandomStatus())).count();
        assetsRandomStock.setBadNum(TypeUtils.castToInt(count));
        assetsRandomStock.setUpdateTime(new Date());
        assetsRandomStock.setStatus("2");
        this.updateById(assetsRandomStock);

    }

    @Override
    public void refresh(String billNo) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("bill_no", billNo);
        AssetsRandomStock one = this.getOne(qw);
        //获取当前抽盘明细
        QueryWrapper<AssetsRandomStockItem> qwStockItem = new <AssetsRandomStockItem>QueryWrapper();
        qwStockItem.eq("apply_id", one.getId());
        List<AssetsRandomStockItem> assetsRandomStockItems = storageRandomStockItemMapper.selectList(qwStockItem);
        if (CollectionUtils.isNotEmpty(assetsRandomStockItems)) {
            //更新抽盘列表
            for (AssetsRandomStockItem assetsRandomStockItem : assetsRandomStockItems) {
                QueryWrapper itemQw = new QueryWrapper();
                itemQw.eq("asset_coding", assetsRandomStockItem.getAssetCoding());
                itemQw.eq("company", assetsRandomStockItem.getCompany());
                AssetsItem assetsItem = assetsItemMapper.selectOne(itemQw);
                assetsRandomStockItem.setDeptId(assetsItem.getDept());
                assetsRandomStockItem.setDeptName(assetsItem.getSimpleDeptName());
                assetsRandomStockItem.setUserer(assetsItem.getUserer());
                assetsRandomStockItem.setOwner(assetsItem.getOwner());
                assetsRandomStockItem.setUpdateTime(new Date());
                storageRandomStockItemMapper.updateById(assetsRandomStockItem);
            }
        }


    }


    /**
     * 保存盘点资产明细
     *
     * @param assetsItem
     * @param assetsRandomStock
     */
    void saveStockItem(OptionAssetsItemDTO optionAssetsItemDTO, AssetsRandomStock assetsRandomStock) {
        if(CollectionUtils.isNotEmpty(optionAssetsItemDTO.getAssetsRandomStockItemList())){
            //则进行插入
            for (AssetsRandomStockItem assetsRandomStockItem : optionAssetsItemDTO.getAssetsRandomStockItemList()) {
                assetsRandomStockItem.setApplyId(assetsRandomStock.getId());
                assetsRandomStockItem.setCreateTime(new Date());
                assetsRandomStockItem.setUpdateTime(new Date());
                assetsRandomStockItem.setNotInventoryQuantity(0);
                assetsRandomStockItem.setInventoryQuantity(1);
                assetsRandomStockItem.setInventoryStatus("0");
                assetsRandomStockItem.setAssetsLocation(assetsRandomStockItem.getAssetsLocation());
                assetsRandomStockItem.setAssetsNum(1);
                QueryWrapper qw = new QueryWrapper();
                qw.eq("asset_coding", assetsRandomStockItem.getAssetCoding());
                qw.eq("company",assetsRandomStockItem.getCompany());
                qw.eq("apply_id", assetsRandomStock.getId());
                AssetsRandomStockItem one = assetsRandomStockItemService.getOne(qw);
                if (one != null) {
                    assetsRandomStockItem.setId(one.getId());
                    assetsRandomStockItemService.updateById(assetsRandomStockItem);
                } else {
                    this.updateById(assetsRandomStock);
                    assetsRandomStockItemService.save(assetsRandomStockItem);
                }
            }
        }else {
            //获取当前登录用户
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            AssetsRandomStockItem assetsRandomStockItem = optionAssetsItemDTO.getAssetsRandomStockItem();
            assetsRandomStockItem.setApplyId(assetsRandomStock.getId());
            assetsRandomStockItem.setCreateTime(new Date());
            assetsRandomStockItem.setUpdateTime(new Date());
            assetsRandomStockItem.setInventoryStatus("1");
            assetsRandomStockItem.setNotInventoryQuantity(0);
            assetsRandomStockItem.setInventoryQuantity(1);
            assetsRandomStockItem.setAssetsLocation(assetsRandomStockItem.getAssetsLocation());
            assetsRandomStockItem.setAssetsNum(1);
            //通过字典配置公司校验是否需要盘点资产图片
            List<DictModel> lstDic= isysBaseAPI.queryDictItemsByCode("company_photo");
            if(lstDic!=null&&lstDic.stream().count()>0){
                String companyCode=assetsRandomStockItem.getCompany();
                List<DictModel> streamDicModel=lstDic.stream().filter(x->x.getValue().equals(companyCode)).collect(Collectors.toList());
                if(streamDicModel!=null&&streamDicModel.stream().count()>0){
                    if(StringUtils.isEmpty(assetsRandomStockItem.getAssetImageUrl())){
                        throw new RuntimeException("公司【"+companyCode+"】盘点资产需要上传资产图片");
                    }
                }
            }
            if (Objects.equals(assetsRandomStockItem.getRandomStatus(), "2")) {
                //发送企业微信消息
                LoginUser userByRealName = isysBaseAPI.getUserByRealName(assetsRandomStockItem.getUserer());
                wechatUtils.sendRoundmSotckWechatMessage(userByRealName.getId(), assetsRandomStock.getBillNo(), assetsRandomStockItem.getAssetName(), user.getRealname());
            }
            QueryWrapper qw = new QueryWrapper();
            qw.eq("asset_coding", assetsRandomStockItem.getAssetCoding());
            qw.eq("company", assetsRandomStockItem.getCompany());
            qw.eq("apply_id", assetsRandomStock.getId());
            AssetsRandomStockItem one = assetsRandomStockItemService.getOne(qw);
            if (one != null) {
                assetsRandomStockItem.setId(one.getId());
                assetsRandomStockItemService.updateById(assetsRandomStockItem);
            } else {
                this.updateById(assetsRandomStock);
                assetsRandomStockItemService.save(assetsRandomStockItem);
            }
        }


    }
}
